package com.spic.business.blast.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spic.business.blast.domain.BlastDeployment;
import com.spic.business.blast.domain.BlastDeploymentWeigh;
import com.spic.business.blast.domain.WeightData;
import com.spic.business.blast.domain.vo.StatisticsWeighInfoVo;
import com.spic.business.blast.mapper.BlastDeploymentWeighMapper;
import com.spic.business.blast.service.BlastWeightService;
import com.spic.business.blast.service.IBlastDeploymentService;
import com.spic.business.blast.service.IBlastDeploymentWeighService;
import com.spic.business.common.core.utils.DateUtil;
import com.spic.common.core.text.UUID;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.system.api.RemoteNoticeInfoService;
import com.spic.system.api.domain.SysNoticeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 称重信息Service业务层处理
 *
 * @author spic
 * @date 2022-03-09
 */
@Service
public class BlastDeploymentWeighServiceImpl implements IBlastDeploymentWeighService
{
    @Autowired
    private BlastDeploymentWeighMapper blastDeploymentWeighMapper;
    @Autowired
    private IBlastDeploymentService blastDeploymentService;
    @Autowired
    private RemoteNoticeInfoService remoteNoticeInfoService;

    /**
     * 查询称重信息
     *
     * @param id 称重信息主键
     * @return 称重信息
     */
    @Override
    public BlastDeploymentWeigh selectBlastDeploymentWeighById(String id)
    {
        return blastDeploymentWeighMapper.selectBlastDeploymentWeighById(id);
    }

    /**
     * 查询称重信息列表
     *
     * @param blastDeploymentWeigh 称重信息
     * @return 称重信息
     */
    @Override
    public List<BlastDeploymentWeigh> selectBlastDeploymentWeighList(BlastDeploymentWeigh blastDeploymentWeigh)
    {
        return blastDeploymentWeighMapper.selectBlastDeploymentWeighList(blastDeploymentWeigh);
    }

    //统计
    @Override
    public List<StatisticsWeighInfoVo> selectstatisticsWeighInfo(BlastDeploymentWeigh blastDeploymentWeigh)
    {
        List<StatisticsWeighInfoVo> list = new ArrayList<>();
        StatisticsWeighInfoVo wighInfo = getWighInfo(blastDeploymentWeigh);
        list.add(wighInfo);
        return list;
    }

    public StatisticsWeighInfoVo getWighInfo(BlastDeploymentWeigh blastDeploymentWeigh){
        List<BlastDeploymentWeigh> blastDeploymentWeighs = blastDeploymentWeighMapper.selectBlastDeploymentWeighList(blastDeploymentWeigh);
        //倒序
        List<BlastDeploymentWeigh> collect = blastDeploymentWeighs.stream().sorted(Comparator.comparing(BlastDeploymentWeigh::getCreateTime,Comparator.reverseOrder())).collect(Collectors.toList());

        StatisticsWeighInfoVo statisticsWeighInfoVo = new StatisticsWeighInfoVo();
        if(collect!=null && collect.size()>0){
            String sum = collect.stream().mapToDouble(b -> b.getDieselConsumption().doubleValue()).sum()+"";
            BigDecimal bigDecimal = new BigDecimal(sum);

            String sum2 = collect.stream().mapToDouble(b -> b.getNetWeight().doubleValue()).sum()+"";
            BigDecimal bigDecimal2 = new BigDecimal(sum2);

            //油耗(kg)
            statisticsWeighInfoVo.setDieselConsumption(bigDecimal);
             //实际用量
            BigDecimal blastDeploymentTotal = collect.get(0).getBlastDeploymentTotal();
            //炸药净重总量(称重净重/kg)
            statisticsWeighInfoVo.setExplosiveTotal(bigDecimal2.subtract(bigDecimal));

            //脚线
            statisticsWeighInfoVo.setFootLine(collect.get(0).getFootLine());

            //起爆弹
            statisticsWeighInfoVo.setEetonatingBomb(collect.get(0).getEetonatingBomb());
            //雷管个数
            statisticsWeighInfoVo.setTotalElectronicDetonator(collect.get(0).getTotalElectronicDetonator());
            //炸药预估总量(预估量/kg)
            statisticsWeighInfoVo.setExplosiveActualUsage(blastDeploymentTotal);

            BigDecimal subtract = blastDeploymentTotal.subtract(statisticsWeighInfoVo.getExplosiveTotal());
            //差值(预估总量-净重总量/kg)
            statisticsWeighInfoVo.setDifferenceValue(subtract);

        }

        //称重日期
        statisticsWeighInfoVo.setWeighDate(blastDeploymentWeigh.getWeighDate());

                //误差范围
        statisticsWeighInfoVo.setAllowableErrorRange(new BigDecimal("20"));
        return statisticsWeighInfoVo;
    }

    /**
     * 新增称重信息
     *
     * @param blastDeploymentWeigh 称重信息
     * @return 结果
     */
    @Override
    public AjaxResult insertBlastDeploymentWeigh(BlastDeploymentWeigh blastDeploymentWeigh)
    {
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        String date = sd.format(new Date());
        List<BlastDeployment> blastDeployments = blastDeploymentService.selectBlastDeploymentListByDate(date);
        if(blastDeployments!=null && blastDeployments.size()>0){
            String sum = blastDeployments.stream().mapToDouble(b -> b.getTotalExplosiveDosage().doubleValue()).sum()+"";
            BigDecimal bigDecimal = new BigDecimal(sum);
            int eetonatingBomb = blastDeployments.stream().mapToInt(b->Integer.parseInt("".equals(b.getEetonatingBomb())?"0":b.getEetonatingBomb())).sum();
            int totalElectronicDetonator = blastDeployments.stream().mapToInt(b->b.getTotalElectronicDetonator()).sum();
            double footLine = blastDeployments.stream().mapToDouble(b -> Double.parseDouble("".equals(b.getFootLine())?"0":b.getFootLine())).sum();
            blastDeploymentWeigh.setBlastDeploymentTotal(bigDecimal);
            blastDeploymentWeigh.setEetonatingBomb(eetonatingBomb+"");
            blastDeploymentWeigh.setFootLine(footLine+"");
            //雷管个数
            blastDeploymentWeigh.setTotalElectronicDetonator(totalElectronicDetonator);
        }else{
            return AjaxResult.error("今日爆破任务不存在！");
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        blastDeploymentWeigh.setId(uuid);
        blastDeploymentWeigh.setWeighDate(DateUtils.getNowDate());
        blastDeploymentWeigh.setCreateTime(DateUtils.getNowDate());
        blastDeploymentWeighMapper.insertBlastDeploymentWeigh(blastDeploymentWeigh);
        return AjaxResult.success("新增成功");
    }
    /**
     * 修改称重信息
     *
     * @param blastDeploymentWeigh 称重信息
     * @return 结果
     */
    @Override
    public int updateBlastDeploymentWeigh(BlastDeploymentWeigh blastDeploymentWeigh)
    {
        blastDeploymentWeigh.setUpdateTime(DateUtils.getNowDate());
        return blastDeploymentWeighMapper.updateBlastDeploymentWeigh(blastDeploymentWeigh);
    }

    /**
     * 批量删除称重信息
     *
     * @param ids 需要删除的称重信息主键
     * @return 结果
     */
    @Override
    public int deleteBlastDeploymentWeighByIds(String[] ids)
    {
        return blastDeploymentWeighMapper.deleteBlastDeploymentWeighByIds(ids);
    }

    /**
     * 删除称重信息信息
     *
     * @param id 称重信息主键
     * @return 结果
     */
    @Override
    public int deleteBlastDeploymentWeighById(String id)
    {
        return blastDeploymentWeighMapper.deleteBlastDeploymentWeighById(id);
    }
    @Autowired
    private BlastWeightService blastWeightService;

    @Override
    public BlastDeploymentWeigh getWeighInfo(BlastDeploymentWeigh blastDeploymentWeigh)
    {
        QueryWrapper<WeightData> queryWrapper=new QueryWrapper<>();
        BlastDeploymentWeigh weigh = new BlastDeploymentWeigh();
        String carCodeType = blastDeploymentWeigh.getCarCodeType();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        String date = sd.format(new Date());
        Date format = DateUtil.format(date, "yyyy-MM-dd");
        //wrapper.eq相当于Map.put,放的是查询条件
        queryWrapper.eq("car_no",carCodeType);
        queryWrapper.eq("cz_date",format);
        queryWrapper.eq("status","是");
        //排序
        queryWrapper.orderByDesc("cz_time2");

        List<WeightData> list = blastWeightService.list(queryWrapper);
        if(list!=null && list.size()>0){
            weigh.setWeightDataList(list);
        }
        return weigh;
    }

    /**
     * 称重告警
     * @return
     */
    @Override
    public String getWeighAlarm() {
        BlastDeploymentWeigh blastDeploymentWeigh = new BlastDeploymentWeigh();
//        blastDeploymentWeigh.setWeighDate(DateUtil.format("2022-03-10","yyyy-MM-dd"));
        blastDeploymentWeigh.setWeighDate(DateUtil.format2(new Date(),"yyyy-MM-dd"));
        StatisticsWeighInfoVo wighInfo = getWighInfo(blastDeploymentWeigh);
        BigDecimal differenceValue = wighInfo.getDifferenceValue(); //称重-使用量 =差值
        BigDecimal allowableErrorRange = wighInfo.getAllowableErrorRange(); //误差范围

        if(StringUtils.isNotNull(differenceValue) ||  StringUtils.isNotNull(allowableErrorRange)){
            if(differenceValue.compareTo(allowableErrorRange)>-1){
                SysNoticeInfo sysNoticeInfo = new SysNoticeInfo();
                sysNoticeInfo.setContent("日期："+DateUtil.fmtDateToStr(wighInfo.getWeighDate(),"yyyy-MM-dd")+"任务名称为:"+wighInfo.getBlastDeploymentTaskName()+":使用量和称重量不一致！");
                sysNoticeInfo.setTitle("爆破布防-称重超出范围");
                sysNoticeInfo.setUserId("1");
                remoteNoticeInfoService.add(sysNoticeInfo);
                return "success";
            }
        }
        return "error";
    }

}
